/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shockwave.pdfium.demo.slice;

import com.shockwave.pdfium.PdfDocument;
import com.shockwave.pdfium.PdfiumCore;
import com.shockwave.pdfium.demo.ResourceTable;
import com.shockwave.pdfium.demo.util.GetFile;
import com.shockwave.pdfium.util.LogUtil;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.TextField;
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * LoadDesiredPage extends AbilitySlice
 */
public class LoadDesiredPage extends AbilitySlice {
    private static final String TAG = PasswordPDFRender.class.getName();
    private static final String FILE_PATH = "entry/resources/rawfile/sample.pdf";
    private static final String FILE_NAME = "sample.pdf";
    TextField text;
    Component ivComp;
    Button open;
    int pageCount;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_desriedpage);

        text = (TextField) findComponentById(ResourceTable.Id_page_num);
        open = (Button) findComponentById(ResourceTable.Id_open_page);
        try {
            findCount(getContext());
        } catch (IOException ex) {
            LogUtil.error(TAG, ex.getMessage());
        }
        open.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                try {
                    if (!(text.getText().isEmpty())) {
                        if (Integer.parseInt(text.getText()) >= 0 && Integer.parseInt(text.getText()) < pageCount) {
                            text.setVisibility(Component.HIDE);
                            open.setVisibility(Component.HIDE);
                            openPdf(getContext());
                    } else {
                        LogUtil.error(TAG, "PageNumber is incorrect");
                    }
                    }
                } catch (IOException ex) {
                    LogUtil.error(TAG, ex.getMessage());
                }
            }
        });
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    private void findCount(Context context) throws IOException {
        try {
            RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry(FILE_PATH);
            File file = GetFile.getFileFromRawFile(FILE_NAME, rawFileEntry, getCacheDir());
            FileDescriptor fd = new RandomAccessFile(file, "r").getFD();
            PdfiumCore pdfiumCore = new PdfiumCore(context);
            PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
            pageCount = pdfiumCore.getPageCount(pdfDocument);
            pdfiumCore.closeDocument(pdfDocument);
        }   catch(IOException ex) {
            LogUtil.error(TAG, ex.getMessage());
        }
    }

    private void openPdf(Context ctx) throws IOException {
        ivComp = findComponentById(ResourceTable.Id_myimg);
        Image iv = null;
        if (ivComp instanceof  Image) {
            iv = (Image) ivComp;
        }
        if (iv != null) {
            int pageNum = Integer.parseInt(text.getText());
            RawFileEntry rawFileEntry = getResourceManager().getRawFileEntry(FILE_PATH);
            File file = GetFile.getFileFromRawFile(FILE_NAME, rawFileEntry, getCacheDir());
            FileDescriptor fd = new RandomAccessFile(file, "r").getFD();
            PdfiumCore pdfiumCore = new PdfiumCore(ctx);
            try {
                PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
                pdfiumCore.openPage(pdfDocument, pageNum);

                PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
                initializationOptions.pixelFormat = PixelFormat.RGB_565;
                initializationOptions.size = new Size(1000, 2000);
                PixelMap pixelMap = PixelMap.create(initializationOptions);
                pdfiumCore.renderPageBitmap(pdfDocument, pixelMap, pageNum, 0, 0, 1000, 2000);
                iv.setPixelMap(pixelMap);

                pdfiumCore.closeDocument(pdfDocument); // important!

            } catch (IOException ex) {
                LogUtil.error(TAG, ex.getMessage());
            }
        }
    }
}
